package com.itheima.aspects;

import com.itheima.domain.DTO.LoginDTO;
import com.itheima.domain.pojo.EmpLoginLog;
import com.itheima.domain.vo.LoginVO;
import com.itheima.domain.vo.Result;
import com.itheima.exception.CustomerException;
import com.itheima.mapper.EmpLoginLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Author:篍
 * @Date: 2025/07/18 19:39
 * @Description:登录日志
 */
@Aspect
@Component
@Slf4j
public class LoginLogAspects1 {
    @Autowired
    EmpLoginLogMapper empLoginLogMapper;

    @Around("execution(* com.itheima.controller.LoginController.login(*))")
    public Object addLoginLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        EmpLoginLog empLoginLog=new EmpLoginLog();
        //获取登录参数
        Object[] args = proceedingJoinPoint.getArgs();
        LoginDTO loginDTO= (LoginDTO) args[0];
        String username = loginDTO.getUsername();
        String password=loginDTO.getPassword();
        empLoginLog.setUsername(username);
        empLoginLog.setPassword(password);
        //计算耗时
        long start =System.currentTimeMillis();
        empLoginLog.setLoginTime(LocalDateTime.now());
        Result result = (Result) proceedingJoinPoint.proceed();
        long end=System.currentTimeMillis();
        empLoginLog.setCostTime(end-start);
        if(0==result.getCode()){
            empLoginLog.setIsSuccess((short) 0);
        }else {
            empLoginLog.setIsSuccess((short) 1);
            LoginVO data = (LoginVO) result.getData();
            empLoginLog.setJwt(data.getToken());
        }
        empLoginLogMapper.addEmpLoginLog(empLoginLog);
        return result;
    }
}
